<template>
  <div>
    <el-container>
      <el-header>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>排班管理</el-breadcrumb-item>
          <el-breadcrumb-item>排班列表</el-breadcrumb-item>
          <el-breadcrumb-item><el-button type="primary" @click="addDialogVisible = true">添加排班</el-button></el-breadcrumb-item>
          <el-breadcrumb-item><el-button type="primary" @click="UploadDialogVisible = true">上传排班表</el-button></el-breadcrumb-item>
          <el-breadcrumb-item><el-button type="primary" @click="templateDownload">排班模板下载</el-button></el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>
      <el-container>

        <!--存放科室信息-->
        <el-aside width="200px">
          <el-tree :data="depList" :props="{label:'name'}" node-key="value" :highlight-current="true" @node-click="handleNodeClick"></el-tree>
        </el-aside>
        <el-main style="padding: 0;margin-left: 15px;width: auto">
          <el-row :gutter="0">
            <el-col :span="3" v-for="item in dateList">
              <el-card class="box-card" @click.native="clickDate(item)">
                {{item}}
              </el-card>
            </el-col>
          </el-row>
          <div>
            <el-table
                :data="scheList"
                stripe
                style="width: 100%">
              <el-table-column
                  prop="workDate"
                  label="日期"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="params.workTime"
                  label="工作时间段"
                  width="180">
              </el-table-column>
              <el-table-column
                  prop="params.docname"
                  label="姓名"
                  width="130">
              </el-table-column>
              <el-table-column
                  prop="params.professionalTitle"
                  label="职称">
              </el-table-column>
              <el-table-column
                  prop="params.depname"
                  label="科室">
              </el-table-column>
              <el-table-column
                  prop="reservedNumber"
                  label="可预约数">
              </el-table-column>
              <el-table-column
                  prop="availableNumber"
                  label="剩余预约数">
              </el-table-column>
              <el-table-column
                  prop="amount"
                  label="挂号费"
                  width="60"
              >
              </el-table-column>
              <el-table-column
                  label="操作">
                <template slot-scope="scope">
                  <el-button type="warning" size="small" @click="editHandle(scope.row.id)">修改</el-button>
                  <el-popconfirm
                      title="确认删除吗？"
                      @confirm="handleDelete(scope.row.id)"
                  >
                    <el-button slot="reference" type="danger" size="small">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
        title="添加/修改排班"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogVisible=false,sche={params:{}},docList=[]">
      <el-form :model="sche"  ref="addFormRef" label-width="90px">
        <el-form-item label="科室" prop="depcode">
          <el-cascader
              v-model="sche.params.defaultCode"
              ref="depList"
              :options="depList"
              :props="{label:'name'}"
              @change="handleChange"
              :show-all-levels="false"
              clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="医生" prop="docId">
          <el-select v-model="sche.docId" placeholder="请选择">
            <el-option
                :value="item.id"
                v-for="item in docList"
                :key="item.value"
                :label="item.username+'  '+item.professionalTitle"
                >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="workDate">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="sche.workDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排班时间段" prop="workTime">
          <el-select v-model="sche.workTime" placeholder="请选择">
            <el-option
                :value="item.value"
                v-for="item in workTimeList"
                :key="item.value"
                :label="item.label"
                >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可预约数量" prop="reservedNumber">
          <el-input v-model="sche.reservedNumber"></el-input>
        </el-form-item>
        <el-form-item label="挂号费" prop="amount">
          <el-input v-model="sche.amount"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>

    <!--文件上传盒子-->
    <el-dialog
        title="提示"
        :visible.sync="UploadDialogVisible"
        width="30%">

      <el-upload
          class="upload-demo"
          ref="upload"
          action="http://localhost:8080/sche/batchAdd"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :on-remove="handleRemoveFile"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :headers="uploadHeader"
          :limit="1"
          :show-file-list="true"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过500kb</div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="UploadDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import scheApi from '@/api/sche'
import docApi from '@/api/doctor'
import dictApi from "@/api/dict"
import {mapState} from "vuex";
export default {
  name: "Schedule",
  data() {
    return {
      depList:[],
      dateList:[],
      scheList:[],
      fileList:[],
      uploadHeader:{token:this.$store.state.user.token},
      searchObj:{},
      docList:{},
      sche:{params:{}},
      addDialogVisible:false,
      UploadDialogVisible:false,
      workTimeList: [{
        value: 1,
        label: '8:30-10:30'
      }, {
        value: 2,
        label: '10:30-11:30'
      }, {
        value: 3,
        label: '14:30-15:30'
      }, {
        value: 4,
        label: '15:30-17:30'
      }],
    }
  },
  computed:{
    ...mapState(['user'])
  },
  created() {
    this.init()
  },
  methods:{
    handleUploadSuccess(res, file, fileList){
      this.$message.success('文件上传成功')
      this.UploadDialogVisible = false
      return true
    },
    handleUploadError(err, file, fileList){
      let myError=err.toString();//转字符串
      myError=myError.replace("Error: ","") // 去掉前面的" Error: "
      myError=JSON.parse(myError);//转对象
      this.$message.error(myError.msg)
    },
    beforeUpload(file){
      const uploadTypes = ['xls', 'xlsx']
      const filetype = file.name.replace(/.+\./, '')
      const uploadLimit=3
      const isRightSize = (file.size || 0) / 1024 / 1024 < uploadLimit
      if (!isRightSize) {
        this.$message.error('文件大小超过 ' + uploadLimit + 'MB')
        return false
      }

      if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
        this.$message.warning({message: '请上传后缀名为xls或xlsx的附件'})
        return false
      }
      return true
    },
    handleRemoveFile(){

    },
    async handleDelete(id){
      const{data:res} = await scheApi.delete(id)
      if (res.code!==200){
        return this.$message.error("删除失败")
      }else{
        this.$message.success("删除成功")
        await this.getScheList()
      }
    },
    async submitUpload() {
      this.$refs.upload.submit();
    },
    async submitForm(){
      if (this.sche.id){//更改
        const{data:res} = await scheApi.update(this.sche)
        if (res.code!==200){
          this.$message.error("更新失败")
        }else {
          this.$message.success("更新成功")
          await this.getScheList()
        }
      }else{//添加
        const{data:res} = await scheApi.add(this.sche)
        if (res.code!==200){
          return this.$message.error("添加失败")
        }else{
          this.$message.success("添加成功")
        }
      }
      this.addDialogVisible=false
      this.sche={params:{}}
    },

    handleChange(){
      this.sche.depcode = this.$refs["depList"].getCheckedNodes()[0].value;
      //查询出科室下对应的医生列表
      this.findDocList(this.sche.depcode)
    },
    async findDocList(id){
      const{data:res} = await docApi.findByDepcode(id)
      if (res.code!==200){
        return this.$message.error("查询失败")
      }
      this.docList = res.data
    },
    init(){
      this.getDepList()
      this.getDateList()
    },
    //获取所有科室
    async getDepList(){
      const{data:res} = await dictApi.findChildData(86)
      if (res.code!==200){
        return this.$message.error("查询失败")
      }
      this.depList = res.data
    },
    async getDateList(){
      const{data:res} = await scheApi.findSevenDay()
      if (res.code!==200){
        return this.$message.error("查询失败")
      }
      this.dateList = res.data
    },
    handleNodeClick(val,node){
      this.searchObj.depcode = node.data.value
    },
    async clickDate(item){
      this.scheList=[]
      //获取科室编号
      this.searchObj.workDate = item
      if (this.searchObj.depcode==null){
        return this.$message.error("请选择具体的科室进行查询")
      }
      await this.getScheList()
    },
    async getScheList(){
      const {data:res} = await scheApi.find(this.searchObj)
      if(res.code!==200){
        return this.$message.error("查询失败")
      }
      this.scheList = res.data
    },
    templateDownload(){
      window.location.href='https://hosp-lzh.oss-cn-beijing.aliyuncs.com/template.xlsx'
    },
    async editHandle(id){
      this.addDialogVisible = true
      const{data:res} = await scheApi.info(id)
      this.sche = res.data
      await this.findDocList(this.sche.depcode)
    }
  }
}
</script>

<style scoped>
.box-card:hover{
  background-color: cornflowerblue;
  cursor: pointer;
}
</style>